package klk.shop.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import klk.shop.objects.ShoppingCart;

/**
 * Dieses Servlet befindet sich im oberen rechten Bereich des Shops. Es zeigt
 * die Anzahl der sich im Warenkorb befindlichen Artikel und den Gesamtpreis.
 * 
 * @author lueder
 * @version 1.0
 * @since 1.4
 */
public class ShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ShoppingCartServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Properties languageLocale = (Properties) session
				.getAttribute("languageProperty");

		ShoppingCart cart = null;
		int totalAmount = 0;
		DecimalFormat f = new DecimalFormat("#0.00");
		double totalPrice = 0.0;

		cart = (ShoppingCart) request.getSession(false).getAttribute("cart");
		if (cart == null)
			cart = new ShoppingCart();
		totalAmount = cart.getTotalAmount();
		String totalAmountString = (totalAmount > 1) ? languageLocale
				.getProperty("items", "items") : languageLocale.getProperty(
				"item", "item");
		totalPrice = cart.computePrice();

		String path = request.getContextPath() + "/";

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<div class='cart'>");
		out.println("<div class='title'><span class='title_icon'><img src='"
				+ path + "images/cart.gif' alt='' title='' /></span>"
				+ languageLocale.getProperty("mycart", "My Cart") + "</div>");
		out.println("<div class='home_cart_content'>");
		out.println(totalAmount + " x " + totalAmountString
				+ " | <span class='red'>"
				+ languageLocale.getProperty("total", "TOTAL") + ": "
				+ f.format(totalPrice) + "EUR</span>");
		out.println("</div>");
		out.println("<a href='" + path + "shoppingcart' class='view_cart'>"
				+ languageLocale.getProperty("viewcart", "view cart") + "</a>");
		out.println("</div>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
